const mfs = require('./mfs');
const utils = require('./utils');
const ccc = require('./ccc');
const android = require('./android');
const hot = require('./hotupdate');
const replace = require('./replace');
// step 2 读取配置
const configPath = mfs.join(__dirname, 'config.json');
const config = require(configPath);


console.log("config.hotDebug ", config.hotDebug);
// step 1 读取路径
let i = 2;
let packPath = "";
let hotBuild = true;
let buildApk = false;
let isUploadOss = false;
//初始化配置文件
initConfig(process.argv[2]);
while (i < process.argv.length) {
    var arg = process.argv[i];
    switch (arg) {
        case '--path':
        case '-p':
            packPath = process.argv[i + 1];
            i += 2;
            break;
        case '--hot':
        case '-h':
            hotBuild = process.argv[i + 1] == 0 ? false : true;
            i += 2;
            break;
        case '--apk':
        case '-a':
            buildApk = process.argv[i + 1] == 1 ? true : false;
            i += 2;
            break;
        default:
            i++;
            break;
    }
}


const androidConfigPath = mfs.join(__dirname, 'android_config.json');
const backPath = mfs.join(__dirname, 'back.json');
if (!mfs.exists(configPath)) {
    console.log('没有找到配置文件');
    return;
}
config.android_config = require(androidConfigPath);
if (!mfs.exists(backPath)) {
    backConfig = {
        hotVersion: '0',
        versionCode: 0
    };
} else {
    backConfig = require(backPath);
}

const projectPath = mfs.join(__dirname, '..');
// 调用打包
if (utils.isMac()) {
    config.enginePath = '/Applications/CocosCreator/Creator/' + config.engineVer + '/CocosCreator.app/Contents';
} else {
    config.enginePath = 'C:/CocosDashboard/resources/.editors/Creator/' + config.engineVer;
}


// console.log("=========================================开始替换安卓工程配置参数=========================================")
//替换安卓相关参数
replace.replaceAndroidManifest(config);
replace.replaceBuildGradle(config);
replace.replaceGameConst(config);

// console.log("=========================================替换安卓工程配置参数完成=========================================")
// console.log("=========================================可以构建apk了=========================================")
// if (buildApk) {
//     console.log(`=========================================开始构建 ${config.debug == "false" ? "Release" : "Debug"} apk=========================================`)
//     android.pack(config);
//     console.log(`=========================================构建 ${config.debug == "false" ? "Release" : "Debug"} apk 结束=========================================`)
// }

/**构建热更 */
function hotUpdate() {
    console.log("------------------------------------------------------------------------------------------")
    console.log("---------------------------------开始导出热更新资源------------------------------------------")
    console.log("------------------------------------------------------------------------------------------")
    console.log(config);
    console.log("------------------------------------------------------------------------------------------")
    console.log("begin pack hotupdate res");
    return hot.startPack(config);
}

/**上传资源到oss */
function uploadToOss() {
    console.log("-------------------------------------------------------------------------------------------")
    console.log("---------------------------------开始上传热更新资源到OSS--------------------------------------")
    console.log("-------------------------------------------------------------------------------------------")
    console.log("begin upload hotupdate res to oss");
    hot.uploadToOss(config);
}

function pack() {
    console.log("==projectPath:", projectPath)
    config.path = projectPath;
    console.log("===替换版本号配置====");
    replace.replaceAutoConfig(config);
    //构建cocos
    ccc.pack(config);

    //压缩
    compressImg(config);
    //加密
    encryptionImg(config);
    //构建热更新资源
    let configData = hotUpdate();
    //上传OSS
    if (isUploadOss) {
        uploadToOss();
    }
    if (buildApk) {
        console.log(`=========================================开始构建 ${config.debug == "false" ? "Release" : "Debug"} apk=========================================`)
        android.pack(config);
        console.log(`=========================================构建 ${config.debug == "false" ? "Release" : "Debug"} apk 结束=========================================`)
        console.log(`=========================================导出Apk 目录=========================================`)
        console.log(`${mfs.join(__dirname, config.nativePath)}/frameworks/runtime-src/proj.android-studio/app/build/backApk/`)
    }


    console.log(`=============${config.hotDebug ? "测试环境" : "正式环境"}--热更新配置:==============`)
    console.log(JSON.stringify(configData));

    process.exit(0);
}

/**压图 */
function compressImg(config) {
    console.log("=======开始压缩资源=========");
    const compress_cmd = `python3 compressimg.py ${config.nativePath}/assets`
    utils.runShSync(compress_cmd);
    console.log("=====压缩资源完成===========");
}

/**加密 */
function encryptionImg(config) {
    console.log("=======开始加密资源=========");
    const res_path = mfs.join(__dirname, `${config.nativePath}/assets/`);
    console.log("res_path = ", res_path);
    utils.runShSync(`python3 en.py ${res_path}`);
    console.log("=======加密资源完成=========");
}

/**根据命令参数设置一下配置 */
function initConfig(arg) {
    const isDebug = arg.indexOf("debug") != -1;
    const isIos = arg.indexOf("ios") != -1;
    buildApk = arg.indexOf("apk") != -1;
    isUploadOss = arg.indexOf("oss") != -1;
    config.hotDebug = isDebug;
    config.debug = `${isDebug}`

    if (isIos) {
        config.buildPath = config.buildPath_ios;
        config.platform = config.platform_ios;
    }
    config.nativePath = `../${config.buildPath}/jsb-${config.template}`
    console.log("=====config.hotDebug====", config.hotDebug)
    console.log("=====config.debug====", config.debug)
    console.log("=====config.buildPath====", config.buildPath)
    console.log("=====config.nativePath====", config.nativePath)
    console.log("=====config.platform====", config.platform)
}

console.log("\n打包模式      = ", config.hotDebug ? "debug" : "release")
console.log("游戏名称(CH)  = ", config.appName)
console.log("游戏名称(EN)  = ", config.title)
console.log("包名          = ", config.packageName)
console.log("版本号        = ", config.hotDebug ? config.hotVersionDebug : config.hotVersion)
console.log("自动上传OSS   = ", isUploadOss ? "是" : "否")
console.log("自动构建APK   = ", buildApk ? "是" : "否")

console.log('\n输入Y(y)以确认打包 输入N(n)退出打包');

let stdin = process.stdin;
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (key) {
    if (key === '\u0003') {
        console.log("===key===", key);
        process.exit();
    }
    // ctrl-c ( end of text )
    if (key === 'n' || key === 'N') {
        console.log("退出打包");
        process.exit();
    }

    if (key === 'Y' || key === 'y') {
        pack();
    }
    // write the key to stdout all normal like
    process.stdout.write(key);
});
